package juc.c_020;/*
   Talk is cheap. Show me the code.
 */

import org.springframework.util.StopWatch;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description
 * @Date 2021/6/20
 * @Author liudl
 */
public class T10_ReadWriteLock {
    static Lock reentrantLock = new ReentrantLock();
    static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();
    private static int value;

    public static void read(Lock lock) {
        lock.lock();
        try {
            Thread.sleep(500);
            System.out.println("read over!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void write(Lock lock,int v) {
        lock.lock();
        try {
            Thread.sleep(500);
            value = v;
            System.out.printf("value = %s write over!\n",value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(20);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < 18; i++) {
            new Thread(()->{
//                read(reentrantLock);
                read(readLock);
                latch.countDown();
            }).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
//                write(reentrantLock, new Random().nextInt(100));
                write(writeLock, new Random().nextInt(100));
                latch.countDown();
            }).start();
        }
        latch.await();
        stopWatch.stop();
        System.out.println();
        System.out.println(stopWatch.getTotalTimeSeconds()+"秒\n"+stopWatch.prettyPrint());
    }
}
